import * as echarts from './echarts';

Component({
  properties: {
    ec: { type: Object },
    canvasId: { type: String, value: 'ec-canvas' },
    lazyLoad: { type: Boolean, value: false }
  },

  data: {
    isUseNewCanvas: true
  },

  ready() {
    if (!this.data.lazyLoad) {
      this.init();
    }
  },

  methods: {
    init(callback) {
      this.initByOldWay(callback);
    },

    initByOldWay(callback) {
      const version = wx.getSystemInfoSync().SDKVersion;
      if (this.compareVersion(version, '2.9.0') < 0) {
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用canvas 2.0，请升级到最新微信版本后重试。'
        });
        return;
      }

      const query = wx.createSelectorQuery().in(this);
      query.select(`#${this.data.canvasId}`)
        .fields({ node: true, size: true })
        .exec((res) => {
          if (!res || res.length === 0 || !res[0]) {
            console.error('获取canvas节点失败');
            return;
          }

          const canvasNode = res[0].node;
          const ctx = canvasNode.getContext('2d');
          const dpr = wx.getSystemInfoSync().pixelRatio || 1;

          canvasNode.width = res[0].width * dpr;
          canvasNode.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);

          this.chart = echarts.init(canvasNode, null, {
            width: res[0].width,
            height: res[0].height,
            devicePixelRatio: dpr
          });

          canvasNode.setChart(this.chart);

          if (this.data.ec && this.data.ec.option) {
            this.chart.setOption(this.data.ec.option);
          }

          if (callback) {
            callback(this.chart);
          }

          this.triggerEvent('init', { chart: this.chart });
        });
    },

    compareVersion(v1, v2) {
      v1 = v1.split('.');
      v2 = v2.split('.');
      const len = Math.max(v1.length, v2.length);

      while (v1.length < len) {
        v1.push('0');
      }
      while (v2.length < len) {
        v2.push('0');
      }

      for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i]);
        const num2 = parseInt(v2[i]);

        if (num1 > num2) {
          return 1;
        } else if (num1 < num2) {
          return -1;
        }
      }
      return 0;
    },

    setOption(option) {
      if (this.chart) {
        this.chart.setOption(option);
      }
    },

    getChart() {
      return this.chart;
    }
  }
})